package com.sgb.kjwl.view.ui.activity.leaseAsk.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPublichLeaseBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.CarBrandEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.PublishLeaseDataEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LeaseCarBrandEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.house.CarBrandActivity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.machine.PublishLeaseInfoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

/**
 * 求租发布界面(机械,设备,车辆,房产)
 */
public class PublishLeaseInfoActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    @Inject
    PublishLeaseInfoModel viewModel;
    private ActivityPublichLeaseBinding binding;
    private int type;//0机械,1设备,2车辆,3房产
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private Calendar selectedDate;
    private Calendar selectedDate2;
    private List<PickSelectEntity> classDatas;
    private List<List<PickSelectEntity>> typeDatas;
    //    private List<PickSelectEntity> CarBrandDatas;
    private List<UnitEntity> UnitDatas;
    private List<PickSelectEntity> limitTimeDatas;
    private List<PickSelectEntity> driverDatas;
    private List<DictEntity3> allpayway;
    private String content;
    private PublishLeaseDataEntity publishleasedataentity;
    private PublishLeaseDataEntity.RentAddress rentAddress;
    private ArrayList<PickSelectEntity> priceMatchUnitDatas;
    private ArrayList<PickSelectEntity> cartypelist;
    private String area = "";
    private String lat;
    private String lon;
    private String className;
    private String typeName;
    private final String labelName = "求租";
    private String id = "";

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent)
                .machineModule(new MachineModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context, int type) {
        Intent intent = new Intent(context, PublishLeaseInfoActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    public static void start(Context context, int type, String id) {
        Intent intent = new Intent(context, PublishLeaseInfoActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_publich_lease);
        binding.topLayout.ivBack.setOnClickListener(v -> finish());
        binding.setViewModel(viewModel);
        //根据类型加载对应布局信息
        type = getIntent().getIntExtra("type", 0);
        switch (type) {
            case 0:
                binding.topLayout.titleView.setText("机械求租发布");
                binding.timeCourse.setLabelName("进场时间");
                binding.llMachinery.setVisibility(View.VISIBLE);
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.llEquipment.setVisibility(View.GONE);
                binding.llVehicleLease.setVisibility(View.GONE);
                binding.llHouseLease.setVisibility(View.GONE);
                break;
            case 1:
                binding.topLayout.titleView.setText("设备求租发布");
                binding.timeCourse.setLabelName("进场时间");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.machineryDriver.setLabelName("是否自带操作员");
                binding.llMachinery.setVisibility(View.GONE);
                binding.llEquipment.setVisibility(View.VISIBLE);
                binding.llHouseLease.setVisibility(View.GONE);
                binding.llVehicleLease.setVisibility(View.GONE);
                break;
            case 2:
                binding.topLayout.titleView.setText("车辆求租发布");
                binding.timeCourse.setLabelName("使用时间");
                binding.itvType.setLabelName("租赁车型");
                binding.llHouseLease.setVisibility(View.GONE);
                binding.llVehicleLease.setVisibility(View.VISIBLE);
                binding.llMachinery.setVisibility(View.GONE);
                binding.llEquipment.setVisibility(View.GONE);
                binding.llCargo.setVisibility(View.GONE);
                break;
            case 3:
                binding.topLayout.titleView.setText("房产求租发布");
                binding.timeCourse.setLabelName("使用时间");
                binding.llHouseLease.setVisibility(View.VISIBLE);
                binding.llVehicleLease.setVisibility(View.GONE);
                binding.llEquipment.setVisibility(View.GONE);
                binding.llMachinery.setVisibility(View.GONE);
                binding.llCargo.setVisibility(View.VISIBLE);
                binding.address.setHint("请选择(非必选)");
                break;
            default:
                break;
        }
        binding.leaseTime.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
        binding.machineryNum.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
        binding.vehicleNumber.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
        binding.leasePrice.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itvType.setOnWholeItemClickListener(this);
        binding.vehicleBrand.setOnWholeItemClickListener(this);
        binding.itemTvSeries.setOnWholeItemClickListener(this);
        binding.itvFloorStructure.setOnWholeItemClickListener(this);
        binding.area.setOnWholeItemClickListener(this);
        binding.address.setOnWholeItemClickListener(this);
        binding.timeCourse.setOnWholeItemClickListener(this);
        binding.timeDeadline.setOnWholeItemClickListener(this);
        binding.machineryDriver.setOnWholeItemClickListener(this);
        binding.paymentMethod.setOnWholeItemClickListener(this);
        binding.machineryDriver.setOnWholeItemClickListener(this);

        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        binding.include.tvUse.setOnClickListener(v -> binding.include.itemTvTitleEdit.setEditContent(binding.include.tvTitleDefault.getText().toString()));
        binding.include.rlLeaseTitle.setVisibility(View.GONE);
        // 面议还是报价功能
        binding.rbTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutDays.setVisibility(View.GONE);
                    binding.rbTime.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutDays.setVisibility(View.VISIBLE);
                    binding.rbTime.setText("面议");
                }
            }
        });
        //   面议还是报价功能
        binding.rbPrice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutPrice.setVisibility(View.GONE);
                    binding.rbPrice.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutPrice.setVisibility(View.VISIBLE);
                    binding.leasePrice.setText("");
                    binding.leasePrice.setHint("请输入(必填)");
                    binding.rbPrice.setText("面议");
                }
            }
        });
        //        租赁价格展示
        binding.tvPriceUnit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard(binding.tvPriceUnit);
                setSoftWareHide();
                PriceUnitData(type);
            }
        });
        //        立即发布按钮
        binding.publicView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PublishLeaseData();
            }
        });
        //        房产面积
//        binding.houseArea.setOnFocusChangeListener(new android.view.View.
//                OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (!hasFocus) {
//                    // 此处为失去焦点时的处理内容
//
//                }
//            }
//        });

        binding.houseArea.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                area = binding.houseArea.getText().toString();
                setDefaultTitle();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void init() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
        publishleasedataentity = new PublishLeaseDataEntity();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        classDatas = new ArrayList<>();
        typeDatas = new ArrayList<>();
//        unit = new ArrayList<>();
//        estatepriceunit = new ArrayList<>();
//        CarBrandDatas = new ArrayList<>();
        UnitDatas = new ArrayList<>();
        limitTimeDatas = new ArrayList<>();
        driverDatas = new ArrayList<>();
        allpayway = new ArrayList<>();
        cartypelist = new ArrayList<>();
        priceMatchUnitDatas = new ArrayList<>();
        selectedDate = Calendar.getInstance();
        selectedDate2 = Calendar.getInstance();
        viewModel.getAddressModel();//请求省市区数据
        viewModel.getTypeModel();//数据类型
        viewModel.getAllPayWay();//付款方式
        switch (type) {
            case 0:
                viewModel.getUnit();//机械租赁单位
                break;
            case 1:
                viewModel.getRentpriceUnit();
                break;
            case 2:
                viewModel.getModelSelect();//汽车分类
                viewModel.getNeedLeaseCarPrice();//车辆租赁单位
//                viewModel.getCarBrand();//汽车品牌
                break;
            case 3:
                viewModel.getEstatePriceUnit();//房子租赁单位
                break;
            default:
                break;
        }
        for (int i = 1; i < 30; i++) {
            PickSelectEntity timedentity = new PickSelectEntity();
            timedentity.setNo("" + i);
            timedentity.setProjectscale(i + "天");
            limitTimeDatas.add(timedentity);
        }
        //是否带驾驶员（0:是;1:否）
        PickSelectEntity dentity = new PickSelectEntity();
        dentity.setNo("0");
        dentity.setProjectscale("是");
        PickSelectEntity dentity1 = new PickSelectEntity();
        dentity1.setNo("1");
        dentity1.setProjectscale("否");
        driverDatas.add(dentity);
        driverDatas.add(dentity1);
        // TODO: 2020/8/20
        publishleasedataentity.setIsDriver("0");
        binding.machineryDriver.setContent("是");
        String[] priceMatchUnit = new String[]{"台", "辆"};
        for (int i = 1; i < 3; i++) {
            PickSelectEntity timedentity = new PickSelectEntity();
            timedentity.setNo("" + i);
            timedentity.setProjectscale(priceMatchUnit[i - 1]);
            priceMatchUnitDatas.add(timedentity);
        }
        binding.llMachineryNumType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMatchPriceUnitPop(0);
            }
        });
        binding.llEquipmentNumType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMatchPriceUnitPop(1);
            }
        });
//        binding.llVehicleNumberType.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showMatchPriceUnitPop(2);
//            }
//        });

        id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            viewModel.getDeviceDetail(id, String.valueOf(type));
        }

    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_type://租赁类型
                if (type == 2) {
                    showcarTypePop();
                } else {
                    showClassTypePop(type);
                }
                break;
            case R.id.vehicle_brand://车辆品牌
                CarBrandActivity.start(PublishLeaseInfoActivity.this);
//                showCarBrandPop();
                break;
            case R.id.item_tv_series://获取车系列表
                if (TextUtils.isEmpty(binding.vehicleBrand.getContent())) {
                    MToast.showToast(this, "请选择车辆品牌");
                    return;
                }
                viewModel.getCarSeries(publishleasedataentity.getRentalBrandId());
                break;
            case R.id.area://所在地址
                if (addressEntityList != null) {
                    showCityPop("请选择地区", 1);
                }
                break;
            case R.id.address:
                if (!TextUtils.isEmpty(binding.area.getContent())) {
                    //跳转详细地址界面
                    viewModel.getLocationLL(rentAddress.getProvinceId(), rentAddress.getCityId(), rentAddress.getAreaId());
                } else {
                    MToast.showToast(this, "请选择使用地区");
                }
                break;
            case R.id.time_course://使用时间(进场时间)
                showCourseTimePop();
                break;
            case R.id.time_deadline://报价截止时间
                if (TextUtils.isEmpty(binding.timeCourse.getContent())) {
                    if (type == 0 || type == 1) {
                        MToast.showToast(this, "请选择进场时间");
                    } else {
                        MToast.showToast(this, "请选择使用时间");
                    }
                    return;
                }
                if (null != limitTimeDatas && limitTimeDatas.size() > 0) {
                    showLimitTimePop();
                }
                break;
            case R.id.machinery_driver://是否携带驾驶员
                showDriverPop();
                break;
            case R.id.payment_method://付款方式选择
                showPaymentMethodPop();
                break;
            case R.id.itv_floorStructure://楼层结果
                showFloorPop();
                break;
            default:
                break;

        }
    }

    //    车辆类型的选择
    private void showcarTypePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String classNamec = cartypelist.get(options1).getProjectscale();
            binding.itvType.setContent(classNamec);
            publishleasedataentity.setRentalModelId(cartypelist.get(options1).getNo() + "");
            setDefaultTitle();
        }).build();
        businessOption.setPicker(cartypelist);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //    选择租赁数量的单价
    private void showMatchPriceUnitPop(int num) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = priceMatchUnitDatas.get(options1).getProjectscale();
            if (num == 0) {
                binding.machineryNumType.setText(content);
            } else if (num == 1) {
                binding.equipmentNumType.setText(content);
            } else if (num == 2) {
                binding.vehicleNumberType.setText(content);
            }

        }).build();
        businessOption.setPicker(priceMatchUnitDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //付款方式选择
    private void showPaymentMethodPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = allpayway.get(options1).getName();
            //2020/8/20修改
            publishleasedataentity.setRentalPayMethod(content + "");
            binding.paymentMethod.setContent(content);
        }).build();
        businessOption.setPicker(allpayway);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //   是否携带驾驶员
    private void showDriverPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = driverDatas.get(options1).getProjectscale();
            publishleasedataentity.setIsDriver(driverDatas.get(options1).getNo() + "");
            binding.machineryDriver.setContent(content);
        }).build();
        businessOption.setPicker(driverDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    // 楼层结构选择对话框
    private void showFloorPop() {
        ArrayList<PickSelectEntity> foolList = new ArrayList<>();
        foolList.add(new PickSelectEntity("1", "单层"));
        foolList.add(new PickSelectEntity("2", "多层"));
        int index = 0;
        if ("多层".equals(binding.itvFloorStructure.getContent())) {
            index = 1;
        }
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = foolList.get(options1).getProjectscale();
            binding.itvFloorStructure.setContent(content);
            publishleasedataentity.setFloorStructure(content);
        }).build();
        businessOption.setPicker(foolList);
        businessOption.setSelectOptions(index);
        businessOption.show();
    }

    //进场时间
    private void showCourseTimePop() {
        Calendar dayCalendar = Calendar.getInstance();
        dayCalendar.setTime(new Date());
        dayCalendar.add(Calendar.DAY_OF_MONTH, 1);

        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                binding.timeCourse.setContent(format);
                publishleasedataentity.setUseAndEnterTime(format + "");
                selectedDate2.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate2);
    }

    //报价截止时间
    private void showLimitTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            try {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                if (checkDate(format, binding.timeCourse.getContent())) {
                    return;
                }
                publishleasedataentity.setEndTime(format + " 23:59:59");
                binding.timeDeadline.setContent(format);
                selectedDate.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(Calendar.getInstance(), null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    //日期比较
    private boolean checkDate(String startTime, String endTime) {
        try {
            if (DateUtils.dateTo13Timestamp(endTime) < DateUtils.dateTo13Timestamp(startTime) || startTime.equals(endTime)) {
                if (type == 1 || type == 2) {
                    MToast.showToast(this, "请选择小于进场时间的日期");
                } else {
                    MToast.showToast(this, "请选择小于使用时间的日期");
                }
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

//    //    报价期限
//    private void showLimitTimePop() {
//        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
//            String content = limitTimeDatas.get(options1).getProjectscale();
//            // TODO: 2020/8/20
//            publishleasedataentity.setRentalQuotePeriod(content.replace("天", ""));
//            binding.leaseDeadline.setContent(content);
//        }).build();
//        businessOption.setPicker(limitTimeDatas);
//        businessOption.setSelectOptions(0);
//        businessOption.show();
//    }

//    //品牌选择弹窗
//    private void showCarBrandPop() {
//        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
//            String className = CarBrandDatas.get(options1).getProjectscale();
//            binding.vehicleBrand.setContent(className);
//            publishleasedataentity.setRentalBrandId(CarBrandDatas.get(options1).getNo() + "");
//            carbrandtype = className;
//            binding.defaultTitle.setContent(typename + "" + cartypename + "/" + carbrandtype);
//            binding.itemTvSeries.setContent("");
//            binding.itemTvSeries.setHint("请选择车系");
//        }).build();
//        businessOption.setPicker(CarBrandDatas);
//        businessOption.setSelectOptions(0, 0);
//        businessOption.show();
//    }

    //    选择地址弹窗
    private void showCityPop(String title, int num) {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName = "";
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                }
                String content = addressEntityList.get(options1).getName() + " / " + opt2.get(options1).get(options2).getName() + " / " + areaName;
                cityPosition1 = options1;
                cityPosition2 = options2;
                rentAddress = new PublishLeaseDataEntity.RentAddress();
                if (!TextUtils.isEmpty(areaName)) {
                    rentAddress.setAreaId(opt3.get(options1).get(options2).get(options3).getNo());
                }
                rentAddress.setProvinceId(addressEntityList.get(options1).getId());
                rentAddress.setCityId(opt2.get(options1).get(options2).getNo());
                Log.d("地址：", content);
                rentAddress.setRentalAddress(content);
                binding.area.setContent(content);
                binding.address.setContent("");
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText(title)
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //返回省市区数据加载数据
    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        addressEntityList = data;
        initJsonData();
    }

    //组装省市区数据信息
    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }

    //发布数据
    private void PublishLeaseData() {
        switch (type) {//
            case 0://机械
                if (TextUtils.isEmpty(binding.itvType.getContent())) {
                    MToast.showToast(this, "请选择租赁分类");
                    return;
                }
                if (TextUtils.isEmpty(binding.machineryNum.getText().toString())) {
                    MToast.showToast(this, "请选择租赁数量");
                    return;
                }

                publishleasedataentity.setRentalUnit(binding.machineryNumType.getText().toString());
                publishleasedataentity.setRentalCount(binding.machineryNum.getText().toString());
                publishleasedataentity.setBrandName(binding.itvBrandNameMachinery.getContent());
                publishleasedataentity.setModelName(binding.itvModelNameMachinery.getContent());
                break;
            case 1://设备
                if (TextUtils.isEmpty(binding.itvType.getContent())) {
                    MToast.showToast(this, "请选择租赁分类");
                    return;
                }
                if (TextUtils.isEmpty(binding.equipmentNum.getText().toString())) {
                    MToast.showToast(this, "请选择租赁数量");
                    return;
                }

                publishleasedataentity.setRentalUnit(binding.equipmentNumType.getText().toString() + "");
                publishleasedataentity.setRentalCount(binding.equipmentNum.getText().toString() + "");
                publishleasedataentity.setBrandName(binding.itvBrandNameDevice.getContent());
                publishleasedataentity.setModelName(binding.itvModelNameDevice.getContent());
                break;
            case 2://车辆
                if (TextUtils.isEmpty(binding.itvType.getContent())) {
                    MToast.showToast(this, "请选择租赁车型");
                    return;
                }
//                if (TextUtils.isEmpty(binding.vehicleBrand.getContent())) {
//                    MToast.showToast(this, "请选择品牌");
//                    return;
//                }
                if (TextUtils.isEmpty(binding.vehicleNumber.getText().toString().trim())) {
                    MToast.showToast(this, "请输入租赁数量");
                    return;
                }

                publishleasedataentity.setRentalUnit(binding.vehicleNumberType.getText().toString() + "");
                publishleasedataentity.setRentalCount(binding.vehicleNumber.getText().toString().trim() + "");
                break;
            case 3://房产求租
                if (TextUtils.isEmpty(binding.itvType.getContent())) {
                    MToast.showToast(this, "请选择租赁分类");
                    return;
                }
                if (TextUtils.isEmpty(binding.houseArea.getText().toString())) {
                    MToast.showToast(this, "请输入租赁面积");
                    return;
                }
                if (Double.parseDouble(binding.houseArea.getText().toString()) <= 0) {
                    MToast.showToast(this, "请输入正确面积");
                    return;
                }

//                if (TextUtils.isEmpty(binding.houseCargoInfo.getEditContent())) {
//                    MToast.showToast(this, "请输入存放货物明细");
//                    return;
//                }
                publishleasedataentity.setReatalAreaUnit("㎡");
                publishleasedataentity.setRentalUnit("㎡");
                publishleasedataentity.setStoredDetail(binding.houseCargoInfo.getEditContent() + "");
                break;
        }

        if (TextUtils.isEmpty(binding.area.getContent())) {
            MToast.showToast(this, "请选择使用地区");
            return;
        }
        if (TextUtils.isEmpty(binding.address.getContent()) && type != 3) {//房产求租详细地址为非必填,不做校验
            MToast.showToast(this, "请选择详细地址");
            return;
        }
        if (TextUtils.isEmpty(binding.timeCourse.getContent())) {
            MToast.showToast(this, "请选择进场时间");
            return;
        }
        if (TextUtils.isEmpty(binding.timeDeadline.getContent())) {
            MToast.showToast(this, "请选择报价截止时间");
            return;
        }
        if (TextUtils.isEmpty(binding.paymentMethod.getContent())) {
            MToast.showToast(this, "请选择付款方式");
            return;
        }
        if (TextUtils.isEmpty(binding.leaseUsername.getContent())) {
            MToast.showToast(this, "请填写联系人");
            return;
        }
        if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            MToast.showToast(this, "请填写联系电话");
            return;
        }
        if (!CheckUtils.isPhoneNumberValid(binding.itemTvPhone.getContent())) {
            MToast.showToast(this, "请填写正确的联系电话");
            return;
        }


        if (checkDate(binding.timeDeadline.getContent(), binding.timeCourse.getContent())) {
            return;
        }

        if (rentAddress != null) {
            rentAddress.setLatitude(lat);
            rentAddress.setLongitude(lon);
            rentAddress.setTaskaddr(binding.address.getContent() + "");
        }
        rentAddress.setTaskaddr(binding.address.getContent() + "");

        if (binding.rbTime.isChecked()) {
            publishleasedataentity.setRentalDuration("-1");
        } else {
            if (TextUtils.isEmpty(binding.leaseTime.getText().toString())) {
                MToast.showToast(this, "请填写租赁时长");
                return;
            }
            publishleasedataentity.setRentalDuration(binding.leaseTime.getText().toString() + "");
            publishleasedataentity.setRentalDurationUnit("0");
        }
        if (binding.rbPrice.isChecked()) {
            publishleasedataentity.setRentalPrice("-1");
            publishleasedataentity.setRentalSelectPrice("");
        } else {
            if (TextUtils.isEmpty(binding.leasePrice.getText().toString())) {
                MToast.showToast(this, "请填写期望租金");
                return;
            }
            if (Double.parseDouble(binding.leasePrice.getText().toString()) <= 0) {
                MToast.showToast(this, "请填写大于0的期望租金");
                return;
            }
            publishleasedataentity.setRentalPrice(binding.leasePrice.getText().toString() + "");
        }

        //设置标题参数
        if (!TextUtils.isEmpty(binding.include.itemTvTitleEdit.getEditContent())) {
            publishleasedataentity.setRentalTitle(binding.include.itemTvTitleEdit.getEditContent());
        } else {
            MToast.showToast(this, "请填写标题");
            return;
        }

        // 详细地址
        publishleasedataentity.setRentAddress(rentAddress);
        publishleasedataentity.setCategoryType(type + "");
        publishleasedataentity.setContactPerson(binding.leaseUsername.getContent() + "");
        publishleasedataentity.setContactPhone(binding.itemTvPhone.getContent());
        publishleasedataentity.setRemark(binding.leaseExpand.getEditContent());
        publishleasedataentity.setRentalArea(binding.houseArea.getText().toString() + "");

        viewModel.getequimentLeasing(publishleasedataentity);
    }

    //租赁单位
    private void PriceUnitData(int num) {
        OptionsPickerView build = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            content = UnitDatas.get(options1).getName();
            binding.tvPriceUnit.setText(content);
            publishleasedataentity.setRentalSelectPriceId(UnitDatas.get(options1).getNo());
            publishleasedataentity.setRentalSelectPrice(content);
        }).build();
        build.setPicker(UnitDatas);
        build.setSelectOptions(0);
        build.show();
    }

    //    机械、设备、车辆、房产分类
    private void showClassTypePop(int num) {
        if (classDatas == null || classDatas.size() == 0) return;
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            className = classDatas.get(options1).getProjectscale();
            if (typeDatas.size() == 0 || null == typeDatas.get(options1) || typeDatas.get(options1).size() == 0 || typeDatas.get(options1).get(options2) == null) {

            } else {
                typeName = typeDatas.get(options1).get(options2).getProjectscale();
            }

            if (!TextUtils.isEmpty(typeName)) {
                binding.itvType.setContent(className + " " + typeName);
                publishleasedataentity.setCategoryParentId(classDatas.get(options1).getNo() + "");
                publishleasedataentity.setCategoryChildId(typeDatas.get(options1).get(options2).getNo() + "");
                binding.include.tvTitleDefault.setText(labelName + " " + className + "/" + typeName);
            } else {
                binding.itvType.setContent(className + "");
                publishleasedataentity.setCategoryChildId("");
                binding.include.tvTitleDefault.setText(labelName + "" + className);
            }

            setDefaultTitle();

        }).build();
        businessOption.setPicker(classDatas, typeDatas);
        businessOption.setSelectOptions(0, 0);
        businessOption.show();
    }

    //机械、设备,车辆,房产求租单位
    public void showUnit(List<UnitEntity> list) {
        this.UnitDatas = list;
        if (list.size() > 0) {
            binding.tvPriceUnit.setText(list.get(0).getName());
            publishleasedataentity.setRentalSelectPriceId(list.get(0).getNo());
            publishleasedataentity.setRentalSelectPrice(list.get(0).getName());
        }
    }

    //类型集合
    public void showTypeView(List<AskLeaseItemEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> data) {
        if (type == 0) {//机械
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(0).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
                List<PickSelectEntity> childList = new ArrayList<>();
                for (AskLeaseItemEntity ll : l.getChildren()) {
                    PickSelectEntity child = new PickSelectEntity();
                    child.setNo(ll.getNo());
                    child.setProjectscale(ll.getName());
                    childList.add(child);
                }
                typeDatas.add(childList);
            }
        } else if (type == 1) {//设备
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(1).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
                List<PickSelectEntity> childList = new ArrayList<>();
                for (AskLeaseItemEntity ll : l.getChildren()) {
                    PickSelectEntity child = new PickSelectEntity();
                    child.setNo(ll.getNo());
                    child.setProjectscale(ll.getName());
                    childList.add(child);
                }
                typeDatas.add(childList);
            }
        } else if (type == 2) {//车辆
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(2).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
            }
        } else if (type == 3) {//房产
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(3).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
                List<PickSelectEntity> childList = new ArrayList<>();
                for (AskLeaseItemEntity ll : l.getChildren()) {
                    PickSelectEntity child = new PickSelectEntity();
                    child.setNo(ll.getNo());
                    child.setProjectscale(ll.getName());
                    childList.add(child);
                }
                typeDatas.add(childList);
            }
        }
    }

//    //汽车品牌的展示
//    public void showBrandPopWindow(List<DictEntity3> data) {
//        for (int i = 0; i < data.size(); i++) {
//            PickSelectEntity entity = new PickSelectEntity();
//            entity.setNo(data.get(i).getId());
//            entity.setProjectscale(data.get(i).getName());
//            CarBrandDatas.add(entity);
//        }
//    }

    /**
     * 展示车系列表弹窗
     *
     * @param carPositionList
     */
    public void showVehicleSystemPicker(List<DictEntity3> carPositionList) {
        if (carPositionList.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String content = carPositionList.get(options1).getName();
                binding.itemTvSeries.setContent(content);
                publishleasedataentity.setSeriesNo(carPositionList.get(options1).getId());
                publishleasedataentity.setCarLineName(carPositionList.get(options1).getName());
                setDefaultTitle();
            }).build();
            businessOption.setPicker(carPositionList);
            businessOption.setSelectOptions(0);
            businessOption.show();
        } else {
            MToast.showToast(this, R.string.no_data);

        }

    }

    // 付款方式
    public void getAllPayWay(List<DictEntity3> data) {
        this.allpayway = data;
    }


    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data) {
        rentAddress.setLatitude(data.getLat());
        rentAddress.setLongitude(data.getLng());
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 255) {
                if (data == null) {
                    return;
                }
                lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0) + "";
                lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0) + "";
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                binding.address.setContent(address + "");
            }

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //汽车类型数据列表选择
    public void getModelSelectList(List<DictEntity3> data) {
        for (int i = 0; i < data.size(); i++) {
            PickSelectEntity entity = new PickSelectEntity();
            entity.setNo(data.get(i).getId());
            entity.setProjectscale(data.get(i).getName());
            cartypelist.add(entity);
        }

    }

    //动态设置设置默认标题
    private void setDefaultTitle() {
        switch (type) {
            case 2:
                binding.include.tvTitleDefault.setText("出租" + binding.itvType.getContent());
                if (!TextUtils.isEmpty(binding.vehicleBrand.getContent())) {
                    binding.include.tvTitleDefault.setText("出租" + binding.itvType.getContent() + "/" + binding.vehicleBrand.getContent());
                    if (!TextUtils.isEmpty(binding.itemTvSeries.getContent())) {
                        binding.include.tvTitleDefault.setText("出租" + binding.itvType.getContent() + "/" + binding.vehicleBrand.getContent() + "/" + binding.itemTvSeries.getContent());
                    }
                }
                break;
            case 3:
                if (!TextUtils.isEmpty(area)) {
                    binding.include.tvTitleDefault.setText(labelName + binding.itvType.getContent() + "/" + area + "㎡");
                } else {
                    binding.include.tvTitleDefault.setText(labelName + binding.itvType.getContent());
                }
                break;
            default:
                break;
        }
        binding.include.rlLeaseTitle.setVisibility(View.VISIBLE);
    }

    /**
     * 编辑回显 使用
     *
     * @param detailEditEntity
     */
    public void showDetail(PublishLeaseDataEntity detailEditEntity) {
        this.publishleasedataentity = detailEditEntity;
        rentAddress = detailEditEntity.getRentAddress();
        binding.itvType.setContent(detailEditEntity.getCategoryParentName() + "/" + detailEditEntity.getCategoryChildName());
        binding.machineryNumType.setText(detailEditEntity.getRentalUnit());
        switch (type) {//
            case 0://机械
                binding.machineryDriver.setContent("0".equals(detailEditEntity.getIsDriver()) ? "是" : "否");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.machineryNum.setText(detailEditEntity.getRentalCount());
                if (!TextUtils.isEmpty(publishleasedataentity.getBrandName())) {
                    binding.itvBrandNameMachinery.setContent(publishleasedataentity.getBrandName());
                }
                if (!TextUtils.isEmpty(publishleasedataentity.getModelName())) {
                    binding.itvModelNameMachinery.setContent(publishleasedataentity.getModelName());
                }
                break;
            case 1://设备
                binding.machineryDriver.setContent("0".equals(detailEditEntity.getIsDriver()) ? "是" : "否");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.equipmentNumType.setText(detailEditEntity.getRentalUnit());
                binding.equipmentNum.setText(detailEditEntity.getRentalCount());
                if (!TextUtils.isEmpty(publishleasedataentity.getBrandName())) {
                    binding.itvBrandNameDevice.setContent(publishleasedataentity.getBrandName());
                }
                if (!TextUtils.isEmpty(publishleasedataentity.getModelName())) {
                    binding.itvModelNameDevice.setContent(publishleasedataentity.getModelName());
                }
                break;
            case 2://车辆
                binding.vehicleNumberType.setText(detailEditEntity.getRentalUnit());
                binding.itvType.setContent(detailEditEntity.getRentalModelName());
                binding.vehicleNumber.setText(detailEditEntity.getRentalCount());
                binding.vehicleBrand.setContent(detailEditEntity.getRentalBrandName());
//                binding.itemTvTitleEdit.setEditContent("求租 " + detailEditEntity.getRentalModelName());
                if (!TextUtils.isEmpty(publishleasedataentity.getCarLineName())) {
                    binding.itemTvSeries.setContent(publishleasedataentity.getCarLineName());
                }
                break;
            case 3://房产求租
                binding.machineryNumType.setText("㎡");
                publishleasedataentity.setReatalAreaUnit("㎡");
                binding.paymentMethod.setContent(detailEditEntity.getRentalPayMethod());
                publishleasedataentity.setRentalUnit("㎡");
                binding.houseArea.setText(detailEditEntity.getRentalArea());
                if (!TextUtils.isEmpty(detailEditEntity.getStoredDetail())) {
                    binding.houseCargoInfo.setEditContent(detailEditEntity.getStoredDetail() + "");//存放物品明细
                } else {
                    binding.houseCargoInfo.setEditContent("");//存放物品明细
                }
                if (!TextUtils.isEmpty(publishleasedataentity.getFloorStructure())) {
                    binding.itvFloorStructure.setContent(publishleasedataentity.getFloorStructure());
                }
                break;
        }

        if (!TextUtils.isEmpty(detailEditEntity.getRentalDuration()) && (Double.valueOf(detailEditEntity.getRentalDuration()) >= 0)) {
            binding.leaseTime.setText(detailEditEntity.getRentalDuration());
            binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_unselect);
            binding.layoutDays.setVisibility(View.VISIBLE);
            binding.rbTime.setText("面议");
            publishleasedataentity.setRentalDuration(detailEditEntity.getRentalDuration());
            binding.rbTime.setChecked(false);
        } else {
            binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_select);
            binding.layoutDays.setVisibility(View.GONE);
            publishleasedataentity.setRentalDuration("-1");
            binding.rbTime.setText("您已选择面议，再次点击退出面议");
            binding.rbTime.setChecked(true);
        }
        if (Double.parseDouble(detailEditEntity.getRentalPrice()) >= 0) {
            binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
            binding.rbPrice.setChecked(false);
            publishleasedataentity.setRentalPrice(detailEditEntity.getRentalPrice());
            binding.layoutPrice.setVisibility(View.VISIBLE);
            binding.rbPrice.setText("面议");
            binding.leasePrice.setText(detailEditEntity.getRentalPrice());
            binding.tvPriceUnit.setText(detailEditEntity.getRentalSelectPrice());

        } else {
            binding.rbPrice.setChecked(true);
            publishleasedataentity.setRentalPrice("-1");
            binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
            binding.layoutPrice.setVisibility(View.GONE);
            binding.rbPrice.setText("您已选择面议，再次点击退出面议");
        }
        if (!TextUtils.isEmpty(detailEditEntity.getEndTime())) {
            binding.timeDeadline.setContent(detailEditEntity.getEndTime().substring(0, 10));
        }
        binding.paymentMethod.setContent(detailEditEntity.getRentalPayMethod());
        binding.include.itemTvTitleEdit.setEditContent(detailEditEntity.getRentalTitle());
        binding.leaseUsername.setContent(detailEditEntity.getContactPerson());
        binding.timeCourse.setContent(detailEditEntity.getUseAndEnterTime());
        binding.area.setContent(detailEditEntity.getRentAddress().getRentalAddress());
        binding.address.setContent(detailEditEntity.getRentAddress().getTaskaddr());
        binding.itemTvPhone.setContent(detailEditEntity.getContactPhone());
        binding.leaseExpand.setEditContent(detailEditEntity.getRemark());
    }

    //监听车辆品牌界面发送的选择结果
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LeaseCarBrandEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CAR_BRAND_SELECT) {
            CarBrandEntity brandEntity = (CarBrandEntity) event.getMessageData();
            publishleasedataentity.setRentalBrandId(brandEntity.getId());
            //选择品牌的时候重置车系数据
            binding.vehicleBrand.setContent(brandEntity.getName());
            binding.itemTvSeries.setContent("");
            binding.itemTvSeries.setHint("请输入车系(必填)");
        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 隐藏软键盘
     */
    private void setSoftWareHide() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

}
